from typing import Optional, List
from paddleocr import PaddleOCR

ocr = PaddleOCR(lang="ch", show_log=False, mode="PP-OCRv4")


def get_float_area(data: List[List[float]]) -> float:
    # [[38.0, 59.0], [82.0, 59.0], [82.0, 85.0], [38.0, 85.0]]
    first_loc = data[0]
    third = data[2]
    height = third[0] - first_loc[0]
    width = third[1] - first_loc[1]
    return height * width


def ocr_price(img_path: str) -> Optional[float]:
    result = ocr.ocr(img_path, cls=True)
    if not result or not result[0]:
        return None
    temp_price = {}
    for one in result[0]:
        area_size = get_float_area(one[0])
        ocr_tuple = one[1]
        ocr_string, confidence = ocr_tuple
        try:
            ocr_string = ocr_string.replace("￥", "").strip()
            ocr_string = ocr_string.replace("¥", "").strip()
            ocr_string = ocr_string.replace("*", "").strip()
            if ocr_string.count(".") > 1:
                ocr_string = ocr_string.split(".")[0]

            ocr_float = float(ocr_string)
            temp_price[area_size] = ocr_float

        except Exception as e:
            pass
    keys = temp_price.keys()
    if not keys:
        return None
    max_area = max(keys)
    return temp_price.get(max_area)


demo_img_path = "./crop_img/ae39324287b5e48c76b98475f08628f.jpg"
result = ocr_price(demo_img_path)
print(result)
# 418.6
